#include "server_network.h"
#include <QJsonDocument>
#include <QDebug>

ServerNetwork::ServerNetwork(QObject *parent) : QTcpServer(parent) {
    if (!this->listen(QHostAddress::Any, 12345)) {
        qDebug() << "Server could not start!";
    } else {
        qDebug() << "Server started!";
    }
}

ServerNetwork::~ServerNetwork() {
    for (QTcpSocket *socket : clients) {
        socket->close();
        socket->deleteLater();
    }
    clients.clear();
}


void ServerNetwork::incomingConnection(qintptr socketDescriptor) {
    QTcpSocket *socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);
    clients.append(socket);
    // connect(socket, &QTcpSocket::readyRead, [this, socket]() {
    //     QByteArray data = socket->readAll();
    //     if (!data.isEmpty()) {
    //         qDebug() << "1111";
    //         emit rawDataReceived(socket, data); // 发出原始数据信号
    //     }
    // });

    bufferMap[socket] = QByteArray(); // 为新连接的客户端初始化缓冲区
    connect(socket, &QTcpSocket::readyRead, [this, socket]() {
        QByteArray data = socket->readAll();
        bufferMap[socket].append(data); // 将数据添加到缓冲区

        // 假设消息以换行符作为结束标志，这里可以根据实际情况修改
        while (bufferMap[socket].contains('\n')) {
            int index = bufferMap[socket].indexOf('\n');
            QByteArray completeMessage = bufferMap[socket].left(index);
            bufferMap[socket] = bufferMap[socket].mid(index + 1);

            if (!completeMessage.isEmpty()) {
                emit rawDataReceived(socket, completeMessage); // 发出完整消息的信号
            }
        }
    });

    qDebug() << "New client connected!";
    // 修改 disconnected 信号的处理逻辑
    connect(socket, &QTcpSocket::disconnected, [this, socket]() {
        clients.removeOne(socket);
        bufferMap.remove(socket);
        emit clientDisconnected(socket);  // 发出信号
        socket->deleteLater();
        qDebug() << "Client disconnected, current connections:" << clients.size();
    });

    // connect(socket, &QTcpSocket::disconnected, [this, socket]() {
    //     clients.removeOne(socket);
    //     socket->deleteLater();
    //     qDebug() << "Client disconnected, current connections:" << clients.size();
    // });
    qDebug() << "New client connected, current connections:" << clients.size();
}

void ServerNetwork::sendDataToClient(QTcpSocket *socket, const QByteArray &data) {
    if (socket->isOpen() && socket->state() == QAbstractSocket::ConnectedState) {
        socket->write(data);
        socket->flush();
        qDebug() << "Data sent to client:" << data.left(500); // 打印前50字节
    } else {
        qDebug() << "Failed to send data: socket is not connected";
    }
}

QList<QTcpSocket*> ServerNetwork:: getClients()const{
    return clients;
}
